<?php

namespace app\user\controller;

use app\common\controller\User;
use \jwt\JWT;

class Api extends User
{
    public function _initialize()
    { }
    //生成图形验证码
    public function verify()
    {
        //随机码
        $key = $this->randstr(32, 'captcha');

        $config = [
            'length' => 4,
            'imageH' => 35,
            'imageW' => 120,
            'fontSize' => 16,
            'reset' => false,
            'expire' => 60,
            'useCurve' => false,
        ];
        $captcha = new \captcha\Captcha($config);

        //构造返回参数
        $data['imgkey'] = $key;
        $data['base64img'] = $captcha->entry($key);
        return json(array('code' => 0, 'msg' => '获取成功', 'data' => $data));
    }

    /**
     * 验证图形验证码
     */
    protected function checkcode($code, $id = '')
    {
        $captcha = new \captcha\Captcha();
        return $captcha->check($code, $id);
    }

    /**
     * 登录接口
     */
    public function login()
    {
        $param = input();
        $username = $param['user_name'];
        $password = $param['user_password'];
        if (empty($username) || empty($password)) {
            return json(['msg' => '用户名或者密码不能为空！', 'data' => $param, 'code' => -1]);
        }
        // 验证码验证
        if ($GLOBALS['config']['user']['sys']['user_verify'] == 1) {
            $result = $this->checkcode($param['validate'], $param['key']);
            if (!$result) {
                return json(['msg' => "验证码错误", 'code' => -2]);
            }
        }
        $user = model('User');
        $userinfo = $user->login($username, $password);
        if ($userinfo['user_id']) {
            //判断是否开启邮箱认证
            if (!empty($userinfo['user_email']) && $GLOBALS['config']['user']['sys']['user_reg_email'] == 1 && $userinfo['user_isemail'] == 2) {
                return json(['msg' => '邮箱需要验证', 'code' => -1, 'url' => zanpian_user_url('user/reg/auth'), 'wait' => 1]);
            }
            $info['userid'] = $userinfo['user_id'];
            $info['token'] = $this->createJwt($userinfo['user_id']);
            return json(['data' => $info, 'msg' => '登录成功', 'code' => 1]);
        } else {
            return json(['msg' => $user->getError(), 'code' => -1]);
        }
    }

    /**
     * 注册
     */
    public function reg()
    {
        $param = input();
        if ($GLOBALS['config']['user']['sys']['user_reg']) {
            if ($param['ac'] == 'mobile') {
                $param['user_mobile'] = $param['to'];
            }
            if ($param['ac'] == 'email') {
                $param['user_email'] = $param['to'];
            }
            // 开启手机验证
            if ($GLOBALS['config']['user']['sys']['user_reg_sms'] == 1) {
                if (!model('send')->check_msg($param)) {
                    return json(['msg' => '手机验证码错误', 'code' => -1]);
                }
            } else {
                if ($GLOBALS['config']['user']['sys']['user_verify'] == 1) {
                    //验证码验证
                    $result = $this->checkcode($param['validate'], $param['key']);
                    if (!$result) {
                        return json(['msg' => "验证码错误", 'code' => -2]);
                    }
                }
            }
            $user = model('User');
            $reuslt = $user->reg($param);
            if (false !== $reuslt) {
                //判断是否开启邮件认证
                if (empty($GLOBALS['config']['user']['sys']['user_reg_sms']) && $GLOBALS['config']['user']['sys']['user_reg_email'] == 1 && empty($user_api['openid'])) {
                    $send = model('send');
                    if ($send->msg($param) !== false) {
                        return json(['msg' => '注册成功,邮箱需要验证,验证信息已发至您的邮箱', 'code' => 1, 'url' => zanpian_user_url('user/reg/auth'), 'wait' => 1]);
                    } else {
                        return json(['msg' => '注册成功,邮件发送失败,请联系管理员', 'code' => 1, 'url' => zanpian_user_url('user/reg/auth'), 'wait' => 1]);
                    }
                }
                //是否需要跳转
                return json(['data' => $reuslt['user_id'], 'msg' => '注册成功', 'code' => 1]);
            } else {
                return json(['msg' => $user->getError(), 'code' => -1]);
            }
        } else {
            return $this->error('对不起,暂未对外开放用户注册!', config('site.site_url'));
        }
    }

    //随机数
    protected function randstr($length = 32, $type = 'numandalpha')
    {
        $role = array(
            'numandalpha' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'num' => '0123456789',
            'captcha' => '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY',
        );
        $characters = array_key_exists($type, $role) ? $role[$type] : $role['numandalpha'];
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

    public function createJwt($user_id)
    {
        $key = md5('plain'); //jwt的签发密钥，验证token的时候需要用到
        $time = time(); //签发时间
        $expire = $time + 14400; //过期时间
        $token = array(
            "user_id" => $user_id,
            "iss" => "xichen", //签发组织
            "aud" => "plain", //签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );
        $jwt = JWT::encode($token, $key);
        return $jwt;
    }
}
